package com.blobfish.fiction.common.util;


import cn.hutool.core.collection.CollectionUtil;
import com.blobfish.fiction.book.service.impl.BookServiceImpl;
import com.blobfish.fiction.common.base.knowledge.DataDictKnowledge;
import com.blobfish.fiction.common.download.AddDownloadTaskThread;
import com.blobfish.fiction.common.download.DownloadQueue;
import com.blobfish.fiction.common.download.DownloadThread;
import com.blobfish.fiction.common.model.Book;
import com.jfinal.aop.Aop;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;

import java.util.List;

/**
 * 下载工具
 * 利用阻塞队列实现多线程下载
 * @author huangbo
 */
public class DownloadUtil {
    private static final Log log = Log.getLog(DownloadUtil.class);
    /**
     * 单例模式下定义的自身
     */
    private static DownloadUtil self;
    /**
     * 下载队列
     */
    private DownloadQueue downloadQueue;
    /**
     * 用来保存小说的service
     */
    public BookServiceImpl bookService;
    /**
     * 是否重启
     */
    private boolean isRestart = false;

    private DownloadUtil() {
        // 如果构造方法被重新调用了，则说明重启了
        this.isRestart = true;
        // 要清除掉自动恢复下载任务的任务列表

        this.bookService = Aop.get(BookServiceImpl.class);
        // 创建下载队列
        downloadQueue = new DownloadQueue(PropKit.getInt("downloadQueueSize"), bookService);
        int downloadThreadNum = PropKit.getInt("downloadThreadNum");
        // 创建N个下载线程
        for (int i = 0; i < downloadThreadNum; i++) {
            new DownloadThread("下载线程" + i, downloadQueue, bookService).start();
        }
    }

    public static DownloadUtil getInstance() {
        if (self != null) {
            return self;
        }
        synchronized (DownloadUtil.class) {
            if (self == null) {
                self = new DownloadUtil();
            }
            return self;
        }
    }

    /**
     * 添加定时任务
     */
    public void addTask(String bookNo) {
        new AddDownloadTaskThread("添加下载任务", bookNo, downloadQueue).start();
    }

    /**
     * 断点下载
     */
    public void startBreakpointDownload() {
        // 获取状态为正在下载的小说列表
        List<Book> bookList = bookService.listByState(DataDictKnowledge.BookStateEnum.DOWNLOADING.getDataCode());
        if (CollectionUtil.isEmpty(bookList)) {
            return;
        }
        bookList.forEach(item -> new AddDownloadTaskThread("添加下载任务", item.getBookNo(), downloadQueue, true).start());
    }

    public boolean isRestart() {
        return isRestart;
    }

    public void setRestart(boolean restart) {
        isRestart = restart;
    }
}
